<?php


namespace app\api\controller;


use app\BaseController;
use app\common\model\Config;
use app\common\model\Goods;
use app\common\model\GoodsSku;
use app\common\model\PointsLog;
use app\common\model\ShopManage;
use app\common\model\UserAddress;
use app\common\model\Shop;
use Intervention\Image\ImageManager;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\helper\Str;
use think\Validate;

class Order extends BaseController
{
    /**
     * 订单确认页面
     */
    public function orderSure()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'    => 'require|number',
            'goods_id|商品id'   => 'require|number',
            'sku_id|商品规格id' => 'require|number',
            'num|商品数量'      => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $shop_id = $param['shop_id'];
        $goods_id = $param['goods_id'];
        $sku_id = $param['sku_id'];
        $num = $param['num'];

        $user_address = null;
        //查询商品信息
        $goods = Goods::where(['id' => $goods_id, 'status' => 1])->find();
        if (!$goods) {
            return error('商品信息异常');
        }

        /**
         * 在这里处理 商品限购 的需求
         * 只有商品id 是 这些  就判断 用户是否购买过  如果购买过则不允许购买
         */

        if (in_array($goods_id, ['318', '328', '108', '492'])) {
            if ($num != 1) {
                return error('商品限购数量为1');
            }
            $re = \app\common\model\Order::where('user_id', $user_id)->where('goods_id', $goods_id)->where('status', 'in', '0,1')->find();
            if ($re) {
                return error('每人只能购买一次该商品');
            }
        }

        //查询商品取货地址
        if ($goods->shop_id != 0) {
            $is_must_address = 2;
            $shop = Shop::find($goods->shop_id);
            if (!$shop) {
                return error('取货店铺信息异常');
            }
            if ($shop->status != 1) {
                return error('取货店铺已关店');
            }
        } else {
            $is_must_address = 1;
            //查询店铺信息
            $shop = \app\common\model\Shop::find($shop_id);
            if (!$shop) {
                return error('店铺信息异常');
            }
            if ($shop->status != 1) {
                return error('店铺已打烊');
            }
            //收货地址信息
            $user_address = UserAddress::where(['user_id' => $user_id])
                ->field('id,user_id,name,phone')
                ->order('is_default', 'desc')
                ->find();
        }

        //查询sku信息
        $goods_sku = GoodsSku::where([
            'goods_id' => $goods_id,
            'id'       => $sku_id
        ])->find();
        if (!$goods_sku) {
            return error('商品规格信息异常');
        }
        if ($goods_sku->stock - $num < 0) {
            return error('商品已售罄');
        }

        if ($goods->shop_id != 0 && input('remark', '')) {
            $goods_sku->sku_json = input('remark');
        }
        //整理返回数据
        $data = [
            'is_must_address' => $is_must_address, //是否需要填写收货地址
            'user_address'    => $user_address,  //收货地址信息
            'ship_to_address' => $shop->address,  //收货地址
            'goods_banner'    => $goods_sku->img ?: $goods->img,//商品主图
            'goods_name'      => $goods['name'], //商品名称
            'goods_sku'       => $goods_sku->sku_json,
            'price'           => $goods_sku->price,
            'num'             => $num,
            'total_price'     => $goods_sku->price * $num,
            'shop_name'       => $shop->name,
        ];
        return success($data);
    }

    /**
     * 订单生成 并兑换
     */
    public function orderCreate()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'      => 'require|number',
            'goods_id|商品id'     => 'require|number',
            'sku_id|商品规格id'   => 'require|number',
            'num|商品数量'        => 'require|number',
            'address_id|收货信息' => 'number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $shop_id = $param['shop_id'];
        $goods_id = $param['goods_id'];
        $sku_id = $param['sku_id'];
        $num = $param['num'];
        //查询店铺信息
        $shop = Shop::find($shop_id);
        if (!$shop) {
            return error('店铺信息异常');
        }
        if ($shop->status != 1) {
            return error('店铺已打烊');
        }
        //查询商品信息
        $goods = Goods::where(['id' => $goods_id, 'status' => 1])->find();
        if (!$goods) {
            return error('商品信息异常');
        }
        //查询sku信息
        $goods_sku = GoodsSku::where([
            'goods_id' => $goods_id,
            'id'       => $sku_id
        ])->find();
        if (!$goods_sku) {
            return error('商品规格信息异常');
        }
        if ($goods_sku->stock - $num < 0) {
            return error('商品已售罄');
        }

        //根据商品信息 判断是否需要填写地址
        if ($goods->shop_id == 0) {
            if (!isset($param['address_id'])) {
                return error('请填写收货地址');
            }
            //收货地址信息
            $user_address = UserAddress::where(['user_id' => $user_id])->find($param['address_id']);
            if (!$user_address) {
                return error('地址信息异常');
            }
        }


        //获取当前商家的商圈信息 或者连锁
        if ($shop->district_id) {  //如果是商圈 计算可用积分
            $re = Shop::where('district_id', $shop->district_id)->column('id');
            $shopIdList = array_values($re);
        } else {  //如果是单店铺
            $shopIdList = [$shop_id];
        }
        //获取用户当前用户当前店铺可用积分
        $user_points_model = new PointsLog();
        $user_points = $user_points_model->getUsefulPoints($user_id, $shopIdList);
        //判断用户积分
        $cost_money = $goods_sku->price * $num;
        if ($cost_money > $user_points) {
            return error('当前可用积分不足');
        }
        Db::startTrans();
        try {
            for ($i = 0; $i < $num; $i++) {
                $order_data = [
                    'order_no'      => 'O_' . msectime() . Str::random(3, 1),
                    'user_id'       => $user_id,
                    'shop_id'       => $shop_id,
                    'goods_shop_id' => $goods->shop_id,
                    'goods_id'      => $goods_id,
                    'sku_id'        => $sku_id,
                    'price'         => $goods_sku->price,
                    'pay_status'    => 1,
                    'status'        => 0,
                    'num'           => 1,
                    'remark'        => input('remark', ''),
                ];
                if ($goods->shop_id == 0) {
                    $order_data['name'] = $user_address['name'];
                    $order_data['phone'] = $user_address->phone;
                }
                //判断商品是否自营 如果自营 订单改为 待收货  订单直接完成
                if ($goods->shop_id != 0) {
//                $order_data['express_time'] = time();
                    $order_data['status'] = 1;
                }
                //处理订单信息
                $order = \app\common\model\Order::create($order_data);
                //用户记录减少积分记录
                PointsLog::create([
                    'user_id'        => $user_id,
                    'shop_id'        => $shop_id, //使用哪个店铺的积分
                    'goods_shop_id'  => $goods->shop_id, //获得积分的店铺
                    'num'            => $goods_sku->price,
                    'type'           => 2,
                    'flag'           => 2,
                    'relation_id'    => $order->id,
                    'relation_sheet' => 1, //1:订单表
                ]);
            }
            //商家增加积分
            if ($goods->shop_id != 0) {
                Shop::where('id', $goods->shop_id)->inc('points_one', $cost_money)->update();
            }

            //销量+1 , 库存-1
            $goods->sales += $num;
            $goods->total_stock -= $num;
            $goods->save();
            $goods_sku->stock -= $num;
            $goods_sku->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        return success($order, '兑换成功,请尽快到门店领取');
    }

    /**
     * 订单中心
     */
    public function orderList()
    {
        $type = input('type', 0); // 0:全部  1:待发货 2:待收货 3:已完成
        $param = $this->request->param();
        [$page_size, $page_no] = paginate($param);
        $user_id = $this->request->uid;
        $order_model = new \app\common\model\Order();
        $order_model = $order_model->with([
            'goods' => function ($query) {
                $query->field('id,img,name');
            },
            'shop'  => function ($query) {
                $query->field('id,name');
            },
            'sku'   => function ($query) {
                $query->field('id,sku_json,img,price');
            }
        ])
            ->where([
                'user_id'       => $user_id,
                'pay_status'    => 1,
                'goods_shop_id' => 0,
            ]);

        switch ($type) {
            case 1: //待发货
                $order_model = $order_model->where('status', 0)
                    ->where('express_time', 0);
                break;
            case 2: //待收货
                $order_model = $order_model->where('status', 0)
                    ->where('express_time', '<>', 0)
                    ->where('receive_time', 0);
                break;
            case 3: //已完成
                $order_model = $order_model->where('status', 1);
                break;
            default: //全部
                break;
        }
        $list = $order_model->order('id', 'desc')->limit($page_size * $page_no, $page_size)
            ->field('id,shop_id,goods_id,sku_id,num,goods_shop_id,user_id,price,pay_status,status,refund_status,name,phone,express_time,receive_time,remark,create_time')
            ->select();
        $limit_time = Config::getSelfConfig('订单领取限时');
        foreach ($list as &$v) {
            if ($v->goods_shop_id == 0) {
                //待发货
                if ($v->express_time == 0 && $v->status == 0) {
                    $v->type = 1;  //当type==1 显示退款
                } elseif ($v->receive_time == 0 && $v->status == 0) {
                    //待收货
                    $v->type = 2;
                    $v->express_limit_time = $v->express_time + $limit_time * 24 * 60 * 60;
                    if ($v->express_limit_time < time()) {
                        $v->type = 3; //已完成
                        $v->status = 1;
                        $v->remark = "用户未在规定时间内领取";
                        $v->save();
                    }
                } else {
                    $v->type = 3; //已完成
                    if ($v->refund_status == 2 && $v->status == 3) {
                        $v->type = 4; //已退款
                    }
                }
            } else {
                //处理订单展示
                if ($v->remark) {
                    $v->sku->sku_json = $v->remark;
                }
                $v->type = 3;
                if ($v->refund_status == 2 && $v->status == 3) {
                    $v->type = 4; //已退款
                }
            }
            if ($v['sku']) {
                if ($v['sku']['img']) {
                    if ($v->goods) {
                        $v->goods->img = $v['sku']['img'];
                    }
                }
                if ($v['sku']['price']) {
                    $v->price = $v['sku']['price'];
                }
            }
        }
        return success($list);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
            //此处有一个字段 flag 标识用户是否通过二维码扫码进入
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_info = $this->request->user_info;
        $order = \app\common\model\Order::with([
            'goods'      => function ($query) {
                $query->field('id,img,name')->removeOption('soft_delete');
            },
            'shop'       => function ($query) {
                $query->field('id,name,address,longitude,latitude');
            },
            'sku'        => function ($query) {
                $query->field('id,sku_json,img,price')->removeOption('soft_delete');
            },
            'user'       => function ($query) {
                $query->field('id,nickname,portrait');
            },
            'goods_shop' => function ($query) {
                $query->field('id,name,address,longitude,latitude');
            }
        ])->where([
            'id' => $param['order_id'],
        ])->hidden(['get_code'])
            ->find();
        if (!$order) {
            return error('订单信息异常');
        }
        if ($order['sku']) {
            if ($order['sku']['img']) {
                $order->goods->img = $order['sku']['img'];
            }
            if ($order['sku']['price']) {
                $order->price = $order['sku']['price'];
            }
        }

        $limit_time = Config::getSelfConfig('订单领取限时');
        //判断订单状态
        //如果是 平台产品  type 1:待发货 2:待收货 3:已完成  4:已退款
        if ($order->goods_shop_id == 0) {
            //待发货
            if ($order->express_time == 0 && $order->status == 0) {
                $order->type = 1;
                $order->type_name = '待发货';
            } elseif ($order->receive_time == 0 && $order->status == 0) {
                //待收货
                $order->type = 2;
                $order->type_name = '待收货';
                $order->express_limit_time = $order->express_time + $limit_time * 24 * 60 * 60;
                if ($order->express_limit_time < time()) {
                    $order->type = 6; //超时作废
                    $order->type_name = '超时作废';
                    $order->status = 4;
                    $order->remark = "用户未在规定时间内领取";
                    $order->save();
                }
            } elseif ($order->status == 4) {
                $order->type = 6; //超时作废
                $order->type_name = '超时作废';
            } else {
                $order->type = 3; //已完成
                $order->type_name = '已完成';
                if ($order->status == 3 && $order->refund_status == 2) {
                    $order->type = 4; //已退款
                    $order->type_name = '已退款';
                }
            }
            //平台产品  判断操作人权限
            $order['order_type'] = 0;
            //如果当前的操作人是商家
            $manage = ShopManage::where('user_id', $user_info->id)
                ->where('shop_id', $order['shop_id'])
                ->where('status', 1)
                ->find();
            if ($manage) {
                if ($order['type'] == 1) { //1:待发货
                    $order['order_type'] = 4; //商家 确认 货已到店按钮 显示
                }
                if (isset($param['flag']) && $param['flag'] == 1) {
                    if ($order['type'] == 2 && $order['receive_time'] == 0) {
                        //当商铺管理员 有核销权限 显示核销按钮
                        if (in_array(4, explode(',', $manage['function_arr']))) {
                            $order['order_type'] = 6;
                        }
                    }
                    if ($order['type'] == 3 && $order['receive_time'] == 0) {
                        //当商铺管理员 有核销权限 显示核销按钮
                        if (in_array(4, explode(',', $manage['function_arr']))) {
                            $order['order_type'] = 6;
                        }
                    }
                }
            }

        } else {  //虚拟产品
            $order->type = 3;
            $order->type_name = '待支付';
            if ($order->pay_status == 1) {
                if ($order->receive_time == 0) {
                    $order->type = 3; //已退款
                    $order->type_name = '待核销';
                } else {
                    $order->type = 3; //已退款
                    $order->type_name = '已核销';
                }
            }
            if ($order->refund_status == 2 && $order->status == 3) {
                $order->type = 4; //已退款
                $order->type_name = '已退款';
            }
            //虚拟产品判断操作人权限
            $order['order_type'] = 0;
            //如果当前的操作人是商家
            $manage = ShopManage::where('user_id', $user_info->id)
                ->where('shop_id', $order['goods_shop_id'])
                ->where('status', 1)
                ->find();
            if ($manage) {
                if (isset($param['flag']) && $param['flag'] == 1) {
                    if ($order['type'] == 3 && $order['receive_time'] == 0) {
                        //当商铺管理员 有核销权限 显示核销按钮
                        if (in_array(4, explode(',', $manage['function_arr']))) {
                            $order['order_type'] = 6;
                        }
                    }
                }
            } else {
//            if ($user_info->id == $order['user_id']) {
//                //确认收货
//                if ($order['type'] == 2 && $order['receive_time'] == 0) {
//                    $order['order_type'] = 2;
//                }
//            }
            }
            //如果是虚拟产品 地址需要改成 取货地址
            $order->shop->address = $order->goods_shop->address;
            $order->shop->longitude = $order->goods_shop->longitude;
            $order->shop->latitude = $order->goods_shop->latitude;
            if ($order->remark) {
                $order->sku->sku_json = $order->remark;
            }
        }
        return success($order);
    }

    /**
     * 确认收货
     */
    public function getGoods()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId = $this->request->uid;
        $userInfo = $this->request->user_info;
        $order = \app\common\model\Order::find($param['order_id']);
        if (!$order) {
            return error('订单信息不存在');
        }
        if ($order->pay_status != 1) {
            return error('订单未支付');
        }

        if ($order->receive_time != 0) {
            return error('用户已经取货,请勿重复操作');
        }
        if ($order->user_id != $userId) {
            //判断产品是否为平台产品
            if ($order->goods_shop_id == 0) {  //平台产品
                //如果当前的操作人是商家
                $manage = ShopManage::where('user_id', $userId)
                    ->where('shop_id', $order['shop_id'])
                    ->where('status', 1)
                    ->find();
                if (!$manage) {
                    return error('没有操作权限');
                }
                if (!in_array(4, explode(',', $manage['function_arr']))) {
                    return error('当前用户没有权限');
                }

                if ($order->status != 0) {
                    if ($order->status == 1) {
                        return error('用户已经取货,请勿重复操作');
                    }
                    return error('订单状态异常');
                }

            } else {  //虚拟产品
                //如果当前的操作人是商家
                $manage = ShopManage::where('user_id', $userId)
                    ->where('shop_id', $order['goods_shop_id'])
                    ->where('status', 1)
                    ->find();
                if (!$manage) {
                    return error('没有操作权限');
                }
                if (!in_array(4, explode(',', $manage['function_arr']))) {
                    return error('当前用户没有权限');
                }
            }
        }
        Db::startTrans();
        try {
            $order->receive_time = time();
            $order->status = 1;
            $order->save();
            //同步更新积分记录里的操作人 from_user_id
            PointsLog::where('relation_id', $order->id)->where('relation_sheet', 1)->where('user_id', $order->user_id)->update(['form_user_id' => $userId]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage());
            return error('操作失败');
        }

        return success([], '操作成功');
    }

    /**
     * 添加收货信息
     */
    public function addressAdd()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'name|收件人姓名'     => 'require',
            'phone|收件人电话'    => 'require',
            'is_default|是否默认' => 'require|number', //1:默认 0:不默认
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        if ($param['is_default'] == 1) {
            UserAddress::where(['user_id' => $user_id, 'is_default' => 1])->update(['is_default' => 0]);
        }
        $user_address = UserAddress::create([
            'user_id'    => $user_id,
            'name'       => $param['name'],
            'phone'      => $param['phone'],
            'is_default' => $param['is_default'],
        ]);
        return success($user_address, '添加成功');
    }

    /**
     * 删除地址
     */
    public function addressDelete()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'address_id|地址id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $user_address = UserAddress::where([
            'user_id' => $user_id,
            'id'      => $param['address_id']
        ])->find();
        if ($user_address) {
            $user_address->delete();
        }
        return success([], '删除成功');
    }

    /**
     * 设置默认地址
     */
    public function setDefault()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'address_id|地址id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $user_address = UserAddress::where(['user_id' => $user_id, 'id' => $param['address_id']])->find();
        if (!$user_address) {
            return error('地址信息错误');
        }
        UserAddress::where(['user_id' => $user_id, 'is_default' => 1])->update(['is_default' => 0]);
        $user_address->is_default = 1;
        $user_address->save();
        return success();
    }

    /**
     * 我的收货地址列表
     */
    public function myAddressList()
    {
        $user_id = $this->request->uid;
        $user_address = UserAddress::where(['user_id' => $user_id])->order('is_default', 'desc')->select();
        if (!$user_address) {
            return error('地址信息错误');
        }
        return success($user_address);
    }

    /**
     * 修改收货信息
     */
    public function addressEdit()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'address_id|地址id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;

        $user_address = UserAddress::where('user_id', $user_id)->find($param['address_id']);
        if (!$user_address) {
            return error('地址信息异常');
        }
        unset($param['address_id']);
        if ($param['is_default'] == 1) {
            UserAddress::where(['user_id' => $user_id, 'is_default' => 1])->update(['is_default' => 0]);
        }
        $user_address->save($param);

        return success($user_address, '修改成功');
    }

    /**
     * 获取店铺订单列表
     */
    public function shopOrderList()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
            'user_id|用户id' => 'number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop_id = $param['shop_id'];
        $user_id = $this->request->uid;
        $user_info = $this->request->user_info;

        $a = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)
            ->where('status', 1)
            ->find();
        if (!$a) {
            return error('当前用户没有权限');
        }

        $shop = \app\common\model\Shop::find($shop_id);
        if (!$shop) {
            return error('店铺信息异常');
        }

        $type = input('type', 0); // 0:全部  1:待发货 2:待收货 3:已完成
        [$page_size, $page_no] = paginate($param);

        $order_model = new \app\common\model\Order();
        $order_model = $order_model->with([
            'goods' => function ($query) {
                $query->field('id,img,name')->removeOption('soft_delete');
            },
            'shop'  => function ($query) {
                $query->field('id,name');
            },
            'sku'   => function ($query) {
                $query->field('id,sku_json')->removeOption('soft_delete');
            },
            'user'  => function ($query) {
                $query->field('id,nickname,portrait');
            }
        ])
//            ->where(function ($query) use ($shop_id) {
//                $query->where(['shop_id' => $shop_id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $shop_id);
//            })
            ->where([
                'pay_status' => 1,
            ]);
        switch ($type) {
            case 1: //待发货
                $order_model = $order_model->where('status', 0)
                    ->where('express_time', 0)
                    ->where('goods_shop_id', 0)
                    ->where('shop_id', $shop_id);
                break;
            case 2: //待收货
                $order_model = $order_model->where('status', 0)
                    ->where('goods_shop_id', 0)
                    ->where('shop_id', $shop_id)
                    ->where('express_time', '<>', 0)
                    ->where('receive_time', 0);
                break;
            case 3: //待兑换
                $order_model = $order_model->where('receive_time', 0)
                    ->where('goods_shop_id', $shop_id);
                break;
            case 4: //已完成
                $order_model = $order_model->where('status', 1)
                    ->where('receive_time', '<>', 0)
                    ->where(function ($query) use ($shop_id) {
                        $query->where(['shop_id' => $shop_id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $shop_id);
                    });
                break;
            default: //全部
                $order_model = $order_model
                    ->where(function ($query) use ($shop_id) {
                        $query->where(['shop_id' => $shop_id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $shop_id);
                    });
                break;
        }
        //如果传入用户id 则根据用户id 进行搜索
        if (isset($param['user_id']) && $param['user_id']) {
            $order_model = $order_model->where('user_id', $param['user_id']);
        }
        $list = $order_model->order('id', 'desc')->limit($page_size * $page_no, $page_size)
            ->field('id,goods_shop_id,goods_id,sku_id,num,shop_id,user_id,price,pay_status,status,refund_status,name,phone,express_time,receive_time,remark,create_time')
            ->select()->toArray();
        $limit_time = Config::getSelfConfig('订单领取限时');
        foreach ($list as &$v) {
            if ($v['goods_shop_id'] == 0) {
                //待发货
                if ($v['express_time'] == 0) {
                    $v['type'] = 1;
                } elseif ($v['receive_time'] == 0) {
                    //待收货
                    $v['type'] = 2;
                    $v['express_limit_time'] = $v['express_time'] + $limit_time * 24 * 60 * 60;
                    if ($v['express_limit_time'] < time()) {
                        $v['type'] = 6; //已超时作废
                        $v['status'] = 1;
                        $v['remark'] = "用户未在规定时间内领取";
                        \app\common\model\Order::where('id', $v['id'])->update(['status' => 4, 'remark' => '用户未在规定时间内领取']);
                    }
                } elseif ($v['status'] = 4) {
                    $v['type'] = 6; //已超时作废
                } else { //订单完成
                    $v['type'] = 3;
                }
            } else {
                //处理订单展示
                if ($v['remark']) {
                    $v['sku']['sku_json'] = json_decode($v['remark'], true);
                }
                $v['type'] = 3;
                if ($v['refund_status'] == 2 && $v['status'] == 3) {
                    $v['type'] = 4; //已退款
                }
                if ($v['pay_status'] == 1 && $v['refund_status'] == 0 && $v['status'] == 1 && $v['receive_time'] == 0) {
                    $v['type'] = 5; //待兑换
                }
            }
        }
        return success($list);
    }

    /**
     * 商户确认 货已到店
     */
    public function shopGetGoods()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId = $this->request->uid;
        $userInfo = $this->request->user_info;
        $order = \app\common\model\Order::find($param['order_id']);
        if (!$order) {
            return error('订单信息不存在');
        }
        if ($order->pay_status != 1) {
            return error('订单未支付');
        }
        if ($order->status != 0) {
            if ($order->status == 1) {
                return error('用户已经取货,请勿操作');
            }
            return error('订单状态异常');
        }
        //判断操作者 权限  只有当前店长 可以 操作  货已到店
        if ($userInfo->shop_id != $order->shop_id) {
            //如果当前的操作人是商家
            $manage = ShopManage::where('user_id', $userId)->where('shop_id', $order['shop_id'])
                ->where('status', 1)
                ->find();
            if (!$manage) {
                return error('没有操作权限');
            }
            if (!in_array(1, explode(',', $manage['function_arr']))) {
                return error('当前用户没有权限');
            }
        }

        $order->express_time = time();
        $order->save();
        return success([], '操作成功');
    }

    /**
     * 券 列表
     */
    public function ticketList()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'type|类型id' => 'require|in:1,2',  //1:已核销 2:待核销
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $keyword = input('keyword', '');
        //如果存在关键词 先去查询 店铺或者商品信息
        $shopIdList = [];
        $goodsIdList = [];
        if ($keyword) {
            //店铺信息
            $shopIdList = Shop::where('name', 'like', '%' . $keyword . '%')->column('id');
            //商品信息
            $goodsIdList = Goods::where('name', 'like', '%' . $keyword . '%')->column('id');
        }

        $userId = $this->request->uid;
        [$pageSize, $page] = paginate($param);
        $order = \app\common\model\Order::with([
            'goods'      => function ($query) use ($keyword) {
                $query->field('id,name')->removeOption('soft_delete');
            },
            'sku'        => function ($query) {
                $query->field('id,img')->removeOption('soft_delete');
            },
            'goods_shop' => function ($query) {
                $query->field('id,name');
            }
        ])->where('user_id', $userId)->where('goods_shop_id', '<>', 0)
            ->where('pay_status', 1)
            ->where('status', 1)
            ->where('refund_status', 0);
        if ($shopIdList && $goodsIdList) {
            $order = $order->where(function ($query) use ($shopIdList, $goodsIdList) {
                $query->where('goods_shop_id', 'in', $shopIdList)->whereOr('goods_id', 'in', $goodsIdList);
            });
//            $order = $order->whereRaw('goods_shop_id in :aa OR goods_id in :bb', ['aa' => $shopIdList, 'bb' => $goodsIdList]);
        } elseif ($shopIdList) {
            $order = $order->where('goods_shop_id', 'in', $shopIdList);
        } elseif ($goodsIdList) {
            $order = $order->where('goods_id', 'in', $goodsIdList);
        }
        $order = $order->order('id', 'desc')
            ->limit($page * $pageSize, $pageSize)
            ->field('id,goods_id,goods_shop_id,sku_id,num,status,create_time');
        $type = $param['type'];
        if ($type == 1) { //已核销
            $order = $order->where('receive_time', '<>', 0);
        } else { //待核销
            $order = $order->where('receive_time', 0);
        }
        $order = $order->select();
        return success($order, '获取成功');
    }

    /**
     * 获取券码
     */
    public function getCode()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId = $this->request->uid;
        $order = \app\common\model\Order::with([
            'goods' => function ($query) {
                $query->field('id,img')->removeOption('soft_delete');
            }
        ])->where('pay_status', 1)
            ->where('user_id', $userId)
//            ->where('status', 1)
            ->where('refund_status', 0)->find($param['order_id']);
        if (!$order) {
            return error('订单异常');
        }
        if (!$order->get_code) {
            $qr_code = (new \Wechat())->getUnlimitQRCode('pages/orders/detail', 'flag=1&order_id=' . $order->id);
            if (isset($order->goods) && $order->goods->img) {
                $imageManager = new ImageManager();
                $image = $imageManager->make($qr_code)->resize(430, 430);

                $productImg = $imageManager->make($order->goods->img)->resize(190, null, function ($constraint) {
                    $constraint->aspectRatio();
                });
                $productImg = $productImg->crop(190, 190, 0, (int)(($productImg->height() - 190) / 2));
                $qr_code = $image->insert(yuanImg($productImg->encode()->getEncoded()), 'left-top', 120, 120);
                $qr_code->encode('jpg', 75);
            }
            $order->get_code = 'data:image/jpg;base64,' . base64_encode($qr_code);
            $order->save();
        }
        return success(['code' => $order->get_code], '获取成功');
    }

    /**
     * 平台产品退款
     */
    public function orderRefund()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId = $this->request->uid;
        $orderId = $param['order_id'];
        $order = \app\common\model\Order::where('pay_status', 1)
            ->where('user_id', $userId)
            ->find($orderId);
        if (!$order) {
            return error('订单信息异常');
        }
        if ($order->pay_status != 1) {
            return error('订单未支付,无法退款');
        }
        if ($order->express_time != 0) {
            return error('订单已发货,无法退款');
        }
        if ($order->use_time != 0) {
            return error('当前核销码已核销,无法退款');
        }

        //获取商品信息
        $goods = Goods::withTrashed()->find($order->goods_id);
        if (!$goods) {
            return error('商品信息异常');
        }
        //获取商品品类信息
        $goods_sku = GoodsSku::withTrashed()->find($order->sku_id);
        if (!$goods_sku) {
            return error('商品规格信息异常');
        }
//        //扣除比例
//        $deduct = Config::getSelfConfig('订单退款扣除');
//        //扣除金额
//        $deduct_money = round($order->price * $deduct / 100, 0);
//        if ($deduct_money < 1) {
//            $deduct_money = 1;
//        }
        $deduct_money = 0;
        //退款金额
        $refund_money = $order->price - $deduct_money;
        //退款逻辑

        Db::startTrans();
        try {
            //订单处理
            $order->refund_status = 2;
            $order->status = 3;
            $order->pay_status = 3;
            $order->save();

            //删除积分记录
            PointsLog::where('user_id', $order->user_id)
                ->where('relation_id', $orderId)
                ->useSoftDelete('delete_time', time())->delete();

            //销量+1 , 库存-1
            $goods->sales -= $order->num;
            $goods->total_stock += $order->num;
            $goods->save();
            $goods_sku->stock += $order->num;
            $goods_sku->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage() . $e->getTraceAsString());
        }
        return success([], '退款成功');
    }

    /**
     *  虚拟商品退款
     */
    public function refund()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $userId = $this->request->uid;
        $orderId = $param['order_id'];
        $order = \app\common\model\Order::where('user_id', $userId)
            ->find($orderId);
        if (!$order) {
            return error('订单信息异常');
        }
        if ($order->pay_status != 1) {
            return error('订单未支付,无法退款');
        }
        if ($order->receive_time != 0) {
            return error('当前核销码已核销,无法退款');
        }
        if ($order->goods_shop_id == 0) {
            return error('当前订单无法退款');
        }
        //获取商品信息
        $goods = Goods::withTrashed()->find($order->goods_id);
        if (!$goods) {
            return error('商品信息异常');
        }
        //获取商品品类信息
        $goods_sku = GoodsSku::withTrashed()->find($order->sku_id);
        if (!$goods_sku) {
            return error('商品规格信息异常');
        }
//        //扣除比例
//        $deduct = Config::getSelfConfig('订单退款扣除');
//        //扣除金额
//        $deduct_money = round($order->price * $deduct / 100, 0);
//        if ($deduct_money < 1) {
//            $deduct_money = 1;
//        }
        $deduct_money = 0;
        //退款金额
        $refund_money = $order->price - $deduct_money;
        //退款逻辑

        Db::startTrans();
        try {
            //订单处理
            $order->refund_status = 2;
            $order->status = 3;
            $order->pay_status = 3;
            $order->save();
            //店铺积分退还
            //用户记录 增加积分记录
            PointsLog::where('user_id', $order->user_id)
                ->where('relation_id', $orderId)
                ->useSoftDelete('delete_time', time())->delete();
            //商家减少积分
            Shop::where('id', $order->goods_shop_id)->dec('points_one', $order->price)->update();

            //销量+1 , 库存-1
            $goods->sales -= $order->num;
            $goods->total_stock += $order->num;
            $goods->save();
            $goods_sku->stock += $order->num;
            $goods_sku->save();

            //用户积分增加
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage() . $e->getTraceAsString());
        }
        return success([], '退款成功');
    }

    /**
     * 退款提示
     */
    public function refundPrompt()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $orderId = $param['order_id'];
        $order = \app\common\model\Order::find($orderId);
        //扣除比例
        $deduct = Config::getSelfConfig('订单退款扣除');
        if ($deduct == 0) {
            return success(['msg' => '退款成功后,积分会立即到账!']);
        }
        //扣除金额
        $deduct_money = round($order->price * $deduct / 100, 0);
        if ($deduct_money < 1) {
            $deduct_money = 1;
        }
        return success(['msg' => '退款成功后,积分会立即到账!']);
        return success(['msg' => '退款会扣除' . $deduct . "%，作为退款手续费。手续费金额：" . $deduct_money], '退款会扣除' . $deduct . "%，作为退款手续费。手续费金额：" . $deduct_money);

    }

    /**
     * 检查订单状态
     */
    public function checkOrderStatus()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'order_id|订单id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $orderId = $param['order_id'];
        $order = \app\common\model\Order::find($orderId);
        $a = false;
        if ($order->goods_shop_id == 0 && $order->receive_time != 0 && $order->status == 1) {
            $a = true;
        }
        return success(['flag' => $a]);
    }
}